﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Nb.Common.Ioc
{
    public static class CoreServiceProvider
    {
        static CoreServiceProvider()
        {
            ResetToEmptyProvider();
        }

        /// <summary>
        /// 重置为Empty
        /// </summary>
        public static void ResetToEmptyProvider()
        {
            Current = new EmptyServiceLocator();
        }

        /// <summary>
        /// 获取当前实例，默认为EmptyProvider
        /// </summary>
        public static IServiceLocator Current { get; set; }

        public static T LocateService<T>()
        {
            if (Current == null)
            {
                throw new Exception("CurrentProvider should be inited first！");
            }
            var service = Current.GetInstance<T>();
            return service;
        }
    }

    public class EmptyServiceLocator : IServiceLocator
    {
        public object GetService(Type serviceType)
        {
            return null;
        }

        public object GetInstance(Type serviceType)
        {
            return null;
        }

        public object GetInstance(Type serviceType, string key)
        {
            return null;
        }

        public IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return Enumerable.Empty<object>();
        }

        public TService GetInstance<TService>()
        {
            return default(TService);
        }

        public TService GetInstance<TService>(string key)
        {
            return default(TService);
        }

        public IEnumerable<TService> GetAllInstances<TService>()
        {
            return Enumerable.Empty<TService>();
        }
    }
}